// 系统管理功能模块
class SystemManager {
    constructor() {
        this.currentTab = 'home';
    }

    init() {
        console.log('系统管理界面已初始化');
        this.setupEventListeners();
        this.loadTabContent('home');
    }
    
    // 设置事件监听器
    setupEventListeners() {
        // 手风琴菜单功能
        document.querySelectorAll('.menu-item').forEach(menuItem => {
            menuItem.addEventListener('click', (e) => {
                e.stopPropagation();
                this.toggleAccordion(menuItem);
            });
        });

        // 菜单切换功能
        document.querySelectorAll('.submenu-item').forEach(item => {
            item.addEventListener('click', () => {
                this.switchTab(item);
            });
        });

        // 退出按钮功能
        document.getElementById('logoutBtn').addEventListener('click', () => {
            this.logout();
        });
    }

    // 手风琴菜单切换
    toggleAccordion(menuItem) {
        const targetId = menuItem.getAttribute('data-target');

        // 如果是首页菜单，直接切换到首页
        if (targetId === 'home') {
            // 移除所有菜单项的active类
            document.querySelectorAll('.menu-item').forEach(item => {
                item.classList.remove('active');
            });
            // 添加active类到首页
            menuItem.classList.add('active');

            // 切换到首页内容
            document.querySelectorAll('.tab-container').forEach(tab => {
                tab.classList.remove('active');
            });
            document.getElementById('home').classList.add('active');

            // 更新页面标题
            document.querySelector('.content-header h2').textContent = '首页';

            // 加载首页内容
            this.loadTabContent('home');
            return;
        }

        const submenu = document.getElementById(`${targetId}-submenu`);
        const toggleIcon = menuItem.querySelector('.toggle-icon');

        if (submenu && toggleIcon) {
            if (submenu.classList.contains('show')) {
                submenu.classList.remove('show');
                toggleIcon.classList.remove('fa-chevron-down');
                toggleIcon.classList.add('fa-chevron-right');
            } else {
                submenu.classList.add('show');
                toggleIcon.classList.remove('fa-chevron-right');
                toggleIcon.classList.add('fa-chevron-down');
            }
        }
    }
    
    // 退出功能
    logout() {
        this.showLogoutConfirm();
    }

    // 显示退出确认弹窗
    showLogoutConfirm() {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'logoutConfirmModal';
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content" style="max-width: 400px;">
                <div class="modal-header">
                    <h3>退出确认</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <div style="padding: 20px; font-size: 16px; color: #333;">
                    确定要退出系统吗？
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" id="logout-cancel-btn">取消</button>
                    <button type="button" class="btn btn-danger" id="logout-confirm-btn">确认退出</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        const closeBtn = modal.querySelector('.modal-close-btn');
        const cancelBtn = modal.querySelector('#logout-cancel-btn');
        const confirmBtn = modal.querySelector('#logout-confirm-btn');
        const overlay = modal.querySelector('.modal-overlay');

        const closeModal = () => {
            modal.classList.remove('show');
            setTimeout(() => modal.remove(), 300);
        };

        const confirmLogout = () => {
            // 隐藏系统管理界面
            document.getElementById('systemPage').style.display = 'none';
            // 显示登录页面
            document.getElementById('loginPage').style.display = 'flex';

            // 清空登录表单
            document.getElementById('loginForm').reset();

            // 重新生成验证码
            loginManager.generateCaptcha();

            console.log('用户已退出系统');
            closeModal();
        };

        closeBtn.addEventListener('click', closeModal);
        cancelBtn.addEventListener('click', closeModal);
        overlay.addEventListener('click', closeModal);
        confirmBtn.addEventListener('click', confirmLogout);

        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') closeModal();
        });

        setTimeout(() => modal.classList.add('show'), 10);
    }
    
    // 切换选项卡
    switchTab(item) {
        // 移除所有active类
        document.querySelectorAll('.submenu-item').forEach(i => {
            i.classList.remove('active');
        });
        
        // 添加active类到当前项
        item.classList.add('active');
        
        // 显示对应的选项卡
        const tabId = item.getAttribute('data-tab');
        document.querySelectorAll('.tab-container').forEach(tab => {
            tab.classList.remove('active');
        });
        document.getElementById(tabId).classList.add('active');
        
        // 更新页面标题
        const pageTitle = item.textContent.trim();
        document.querySelector('.content-header h2').textContent = pageTitle;
        
        // 加载对应选项卡的内容
        this.loadTabContent(tabId);
    }
    
    // 加载选项卡内容
    loadTabContent(tabId) {
        this.currentTab = tabId;
        const tabContainer = document.getElementById(tabId);

        // 根据选项卡ID加载不同内容
        switch(tabId) {
            case 'home':
                HomeManager.loadContent(tabContainer);
                break;
            case 'user-management':
                UserManagementManager.loadContent(tabContainer);
                break;
            case 'user-role':
                UserRoleManager.loadContent(tabContainer);
                break;
            case 'org-structure':
                OrgStructureManager.loadContent(tabContainer);
                break;
            case 'permission-system':
                PermissionSystemManager.loadContent(tabContainer);
                break;
            case 'system-params':
                SystemParamsManager.loadContent(tabContainer);
                break;
            case 'resource-library':
                ResourceLibraryManager.loadContent(tabContainer);
                break;
            case 'qa-pairs':
                QAPairsManager.loadContent(tabContainer);
                break;
            case 'case-library':
                CaseLibraryManager.loadContent(tabContainer);
                break;
            case 'topic-management':
                TopicManagementManager.loadContent(tabContainer);
                break;
            case 'tag-management':
                TagManagementManager.loadContent(tabContainer);
                break;
            case 'version-history':
                VersionHistoryManager.loadContent(tabContainer);
                break;
        }
    }
    
    // 搜索功能
    search(tabId) {
        const searchInput = document.querySelector(`#${tabId} .search-area input`);
        const searchText = searchInput.value.toLowerCase();
        const activeTab = document.getElementById(tabId);
        const rows = activeTab.querySelectorAll('tbody tr');
        
        rows.forEach(row => {
            let found = false;
            const cells = row.querySelectorAll('td');
            
            cells.forEach(cell => {
                if (cell.textContent.toLowerCase().includes(searchText)) {
                    found = true;
                }
            });
            
            row.style.display = found ? '' : 'none';
        });
    }
    
    // 设置操作按钮事件
    setupActionButtons(container) {
        const actions = container.querySelectorAll('.actions button');
        actions.forEach(button => {
           if (!button.querySelector('.fa-search') && !button.querySelector('.fa-plus') && !button.querySelector('.fa-edit') && !button.querySelector('.fa-file-import')) { // 排除搜索按钮、所有包含fa-plus图标的新增按钮、包含fa-edit图标的修改按钮和包含fa-file-import图标的批量导入按钮
                button.addEventListener('click', function() {
                    const buttonText = this.textContent.trim();
                    alert(`执行操作: ${buttonText}`);
                });
            }
        });
    }
}

// 初始化系统管理器
const systemManager = new SystemManager();